package com.dragee.modules.work.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.constants.CommonConstants;
import com.dragee.modules.sys.entity.UserEntity;
import com.dragee.modules.sys.service.UserService;
import com.dragee.modules.work.dao.OrderDao;
import com.dragee.modules.work.entity.OrderEntity;
import com.dragee.modules.work.entity.ShopClerkEntity;
import com.dragee.modules.work.entity.ShopEntity;
import com.dragee.modules.work.entity.ShopProjectEntity;
import com.dragee.modules.work.service.*;
import com.dragee.utils.LoginUserUtil;
import com.dragee.utils.StringUtils;
import com.dragee.utils.WrapperUtil;
import com.dragee.utils.excel.CommonListener;
import com.dragee.utils.excel.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {


    @Resource
    private OrderDao orderDao;

    private String business = "order";

    @Autowired
    private ShopProjectService shopProjectService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private UserService userService;
    @Autowired
    private PointsHistoryService pointsHistoryService;
    @Autowired
    private ShopClerkService shopClerkService;



    /**
    * 列表
    */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Long userId = LoginUserUtil.getLoginUserId();
        if (userId == null) {
            // 顾客
            params.put("customerTel", params.get("tel"));
            params.remove("tel");
        } else {
            // 店家
            ShopEntity shop = shopService.getShopByUserId(userId + "");
            if (shop != null) {
                params.put("shopId", shop.getId());
            } else {
                params.put("shopId", null); // 如果不是店家 不能看
            }
        }


        int limit = params.get(CommonConstants.LIMIT) == null
                ?CommonConstants.LIMIT_SIZE:Integer.parseInt(params.get(CommonConstants.LIMIT).toString());
        int start = params.get(CommonConstants.START) == null
                ?CommonConstants.START_SIZE:Integer.parseInt(params.get(CommonConstants.START).toString());

        QueryWrapper<OrderEntity> wrapper =
                WrapperUtil.getWrapper(business, params, OrderEntity.class);
        IPage<OrderEntity> page = new Page<>(start, limit);
        page = baseMapper.selectPage(page, wrapper.select());
        List<OrderEntity> orders = page.getRecords();
        for (OrderEntity order : orders) {
            String projectId = order.getProjectId();
            ShopProjectEntity shopProjectEntity = shopProjectService.getById(projectId);
            order.setProject(shopProjectEntity);
        }
        return new PageUtils(page);
    }


    @Override
    public R importData(MultipartFile file) throws IOException {
        //填充对应词典 sex: (1:男, 2:女)
        Map<String, Map<String,Object>> map = new HashMap<>();
        //解析器
        CommonListener<OrderEntity> commonListener
                = new CommonListener<>(map, OrderEntity.class,this::excelBatch);
        EasyExcel.read(file.getInputStream())
                .head(OrderEntity.class)
                .registerReadListener(commonListener)
                .sheet()
                .doRead();
        List<String> msgList = commonListener.getMsgList();
        if(msgList.size()>0){
            return R.error(StringUtils.join(msgList,","));
        }
        return R.ok();
    }

    @Override
    public void exportData(Map<String, Object> params, HttpServletResponse response) throws Exception {
        QueryWrapper<OrderEntity> wrapper =
                WrapperUtil.getWrapper(business, params, OrderEntity.class);
        List<OrderEntity> datas = list(wrapper);
        ExcelUtils.writeExcel(response,
                datas,
                "订单表" + System.currentTimeMillis(),
                "数据", OrderEntity.class);
    }

    /** 结算积分
     * @param order
     */
    @Override
    public void settlePoints(OrderEntity order) {
        ShopEntity shop = shopService.getById(order.getShopId());
        String personId = shop.getPersonId();
        UserEntity master = userService.getById(personId);
        BigDecimal price = new BigDecimal(order.getPrice());
        String masterPoints = new BigDecimal(master.getPoints()).add(price).toString();
        master.setPoints(masterPoints);
        userService.saveOrUpdate(master);
        pointsHistoryService.addPointsHistory(master.getUserId().toString(),"订单结算", "add",
                masterPoints, order.getId().toString());

        BigDecimal cost = new BigDecimal(order.getManHourCost());
        ShopClerkEntity clerk = shopClerkService.getById(order.getClerkId());
        clerk.setPoints(new BigDecimal(clerk.getPoints()).add(cost).toString());
        shopClerkService.saveOrUpdate(clerk);
        pointsHistoryService.addPointsHistory(clerk.getId().toString(),"订单工时费", "add",
                masterPoints, order.getId().toString());

    }

    /** 导入执行入库方法
     * @param datas
     * @return
     */
    private boolean excelBatch (List<OrderEntity> datas) {
        for (OrderEntity data : datas) {
            saveOrUpdate(data);
        }
        return true;
    }

    @Override
    public List<OrderEntity>  getOrders (String customerTel, String status) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        if (StrUtil.isNotBlank(customerTel)) {
            qw.eq("customerTel", customerTel);
        }
        if (StrUtil.isNotBlank(status)) {
            qw.eq("status", status);
        }
        return list(qw);
    }
}